package com.chen.wx.controller;


import com.chen.wx.handler.WxChatMsgFactory;
import com.chen.wx.handler.WxChatMsgHandler;
import com.chen.wx.utils.MessageUtil;
import com.chen.wx.utils.SHA1;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;

@RestController
@Slf4j

/**
 *
 * @author: ChenFY
 * @date: 2024/6/21
 */
public class CallBackController {
    @Resource
    private WxChatMsgFactory wxChatMsgFactory;


    private static final String token = "adwidhaidwoaid";


    @RequestMapping("/test")
    public String test() {
        return "hello world";
    }

    /**
     * 回调消息校验
     */
    @GetMapping("callback")
    public String callback(@RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam("echostr") String echostr) {
        log.info("get验签请求参数：signature:{}，timestamp:{}，nonce:{}，echostr:{}",
                signature, timestamp, nonce, echostr);
        String shaStr = SHA1.getSHA1(token, timestamp, nonce, "");
        //相等-->解析成功
        if (signature.equals(shaStr)) {
            return echostr;
        }
        //解析不成功
        return "unknown";
    }
    @PostMapping(value = "callback", produces = "application/xml;charset=UTF-8")
    public String callback(
            @RequestBody String requestBody,
            @RequestParam("signature") String signature,
            @RequestParam("timestamp") String timestamp,
            @RequestParam("nonce") String nonce,
            @RequestParam(value = "msg_signature", required = false) String msgSignature) {
        log.info("接收到微信消息：requestBody：{}", requestBody);
        //解析微信返回的xml数据
        Map<String, String> messageMap = MessageUtil.parseXml(requestBody);
        //获取事件类型（关注、文本信息），存入map集合
        String msgType = messageMap.get("MsgType");
        //获取事件，等于空返回空，不为空返回数据,存入map
        String event = messageMap.get("Event") == null ? "" : messageMap.get("Event");
        log.info("msgType:{},event:{}", msgType, event);
        //拼接类型（event.subscribe）
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(msgType);
        if (!StringUtils.isEmpty(event)) {
            stringBuilder.append(".");
            stringBuilder.append(event);
        }
        //toString
        String msgTypeKey = stringBuilder.toString();
        //在wxChatMsgFactory中得到事件类型
        WxChatMsgHandler wxChatMsgHandler = wxChatMsgFactory.getHandlerByMsgType(msgTypeKey);
        if (Objects.isNull(wxChatMsgHandler)) {
            return "unknown";
        }
        //将得到的xml数据放入信息处理器
        String replyContent = wxChatMsgHandler.dealMsg(messageMap);
        log.info("replyContent:{}", replyContent);
        return replyContent;
    }
}
